package io.github.maojian.sort;

import org.junit.Test;

import java.util.Arrays;

/**
 * @Auther: jian.mao
 * @Date: 2022/6/13 10:13
 * @Description: https://leetcode.cn/problems/height-checker/
 */
public class Q1051 {
    public int heightChecker(int[] heights) {
        int[] newHeights = Arrays.copyOf(heights,heights.length);
        Arrays.sort(newHeights);
        int count = 0;
        for (int i = 0; i < heights.length; i++) {
            if (heights[i] != newHeights[i]) {
                count++;
            }
        }
        return count;
    }

    /*
     *  计数排序
     */
    public int heightChecker01(int[] heights) {
        int m = Arrays.stream(heights).max().getAsInt();
        int[] cnt = new int[m + 1];
        for (int h : heights) {
            ++cnt[h];
        }

        int idx = 0, ans = 0;
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= cnt[i]; ++j) {
                if (heights[idx] != i) {
                    ++ans;
                }
                ++idx;
            }
        }
        return ans;
    }

    @Test
    public void test01() {
        int[] heights = new int[]{1, 1, 4, 2, 1, 3};
        System.out.println(heightChecker(heights));
    }

    @Test
    public void test02() {
        int[] heights = new int[]{5, 1, 2, 3, 4};
        System.out.println(heightChecker01(heights));
    }
}
